//
//  LTMessageVoiceBody.m
//  LTIM
//
//  Created by 俊松何 on 2017/4/11.
//  Copyright © 2017年 俊松何. All rights reserved.
//

#import "LTMessageVoiceBody.h"

static const NSString *voicePath = @"chatvoicebuffer";

@implementation LTMessageVoiceBody

- (instancetype)initWithData:(NSData *)aData
                    duration:(NSInteger)duration;
{
    if(self = [super init])
    {
        
        int random = arc4random() % 10000;
        NSString *filename = [NSString stringWithFormat:@"%d%ld.amr",random, (NSInteger)[[NSDate date] timeIntervalSince1970] * 1000];
        
        NSArray *arrDocumentPaths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
        NSString *documentPath=[arrDocumentPaths objectAtIndex:0];
        
        documentPath = [NSString stringWithFormat:@"%@/%@",documentPath,voicePath];
        
        
        
        NSFileManager *fileManager = [NSFileManager defaultManager];
        
        if(![fileManager fileExistsAtPath:documentPath])
        {
            [fileManager createDirectoryAtPath:documentPath withIntermediateDirectories:YES attributes:nil error:nil];
        }
        
        NSString *failePath = [NSString stringWithFormat:@"%@/%@",documentPath,filename];
        _relativelocalPath = [NSString stringWithFormat:@"%@/%@",voicePath,filename];
        _duration  = duration;
        _isPlayed = YES;
        
         [fileManager createFileAtPath:failePath contents:aData attributes:nil];
        
    }
    return self;

}

-(NSString *)localPath
{
    
    NSArray *arrDocumentPaths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *documentPath=[arrDocumentPaths objectAtIndex:0];
    _localPath = [NSString stringWithFormat:@"%@/%@",documentPath,_relativelocalPath];
    
    return _localPath;
    
}
-(void)saveData:(NSData *)data
{

    int random = arc4random() % 10000;
    NSString *filename = [NSString stringWithFormat:@"%d%ld.amr",random, (NSInteger)[[NSDate date] timeIntervalSince1970] * 1000];
    
    NSArray *arrDocumentPaths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *documentPath=[arrDocumentPaths objectAtIndex:0];
    
    documentPath = [NSString stringWithFormat:@"%@/%@",documentPath,voicePath];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    if(![fileManager fileExistsAtPath:documentPath])
    {
        [fileManager createDirectoryAtPath:documentPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    NSString *failePath = [NSString stringWithFormat:@"%@/%@",documentPath,filename];
    _relativelocalPath = [NSString stringWithFormat:@"%@/%@",voicePath,filename];

    
    [fileManager createFileAtPath:failePath contents:data attributes:nil];



}

@end
